package com.pilipili.zeus.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pilipili.servicebase.handler.MyException;
import com.pilipili.zeus.eduService.entity.EduSubject;
import com.pilipili.zeus.eduService.entity.excel.SubjectExcelData;
import com.pilipili.zeus.eduService.service.EduSubjectService;

/**
 * ExcelListener不能交给Spring管理,需自己创建对象
 * 然后传入已创建的对象,才能实现数据库操作
 * @author Unlimited_Blade_Works
 */
public class ExcelListener extends AnalysisEventListener<SubjectExcelData> {

    public EduSubjectService subjectService;

    public ExcelListener() {
    }

    public ExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }
    //按行读取Excel内容
    @Override
    public void invoke(SubjectExcelData subjectExcelData, AnalysisContext analysisContext) {
        if(subjectExcelData ==null){
            throw new MyException(20001,"文件数据为空");
        }
        //查询数据(name,0)是否存在,不存在则将数据写入数据库
        EduSubject existOneSubject = this.existOneSubject(subjectService, subjectExcelData.getOneSubjectName());
        if(existOneSubject==null){
            existOneSubject=new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectExcelData.getOneSubjectName());
            subjectService.save(existOneSubject);

        }
        //查询二级标题是否存在,不存在则将(二级标题,一级标题id)写入数据库
        String id = existOneSubject.getId();
        EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectExcelData.getTwoSubjectName(),id);
        if(existTwoSubject==null){
            existTwoSubject=new EduSubject();
            existTwoSubject.setParentId(id);
            existTwoSubject.setTitle(subjectExcelData.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }
    }
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        return subjectService.getOne(wrapper);
    }
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String id){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",id);
        return subjectService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
